package com.qbccn.bbs.config.custom;

import com.alibaba.fastjson.JSONObject;
import com.qbccn.bbs.domain.BbsUser;
import com.qbccn.bbs.domain.BbsUserMenu;
import com.qbccn.bbs.domain.BbsUserSignSub;
import com.qbccn.bbs.mapper.BbsUserSignSubMapper;
import com.qbccn.bbs.service.MenuService;
import com.qbccn.bbs.service.UserService;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

/**
 * @author linke
 * @date 2020/5/30 19:42
 * @description
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private UserService userService;
  @Autowired
  private BbsUserSignSubMapper bbsUserSignSubMapper;
  @Autowired
  private MenuService menuService;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse, Authentication authentication)
      throws IOException, ServletException {
    User user1 = (User) authentication.getPrincipal();
    BbsUser user = userService.getUser(user1.getUsername());
    user.setPassword(null);
    httpServletRequest.getSession().setAttribute("user", user);
    httpServletRequest.getSession().setAttribute("username", user1.getUsername());
    httpServletRequest.getSession()
        .setAttribute("userLabel", userService.getUserLabel(user.getUsername()));//用户的标签放到session中

    //登录后，初始化用户的菜单
    initMeun(user.getUsername(),httpServletRequest);

    try {
      this.initSign(user.getUsername());
    } catch (Exception e) {
      e.printStackTrace();
    }

    //登录后，返回原访问页面
    RequestCache cache = new HttpSessionRequestCache();
    SavedRequest savedRequest = cache.getRequest(httpServletRequest, httpServletResponse);
    String url = null;
    try {
      url = savedRequest.getRedirectUrl();
    } catch (Exception e) {
      url = "0";
    }
    //登录成功返回
    JSONObject json = new JSONObject();
    json.put("code", "0");
    json.put("message", "登录成功");
    json.put("data", url);
    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setContentType("application/json; charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");
    httpServletResponse.getWriter().write(json.toJSONString());
  }

  /**
   * 初始化用户菜单
   */
  private void initMeun(String username,HttpServletRequest request){
    List<BbsUserMenu> menus= menuService.getMenu(username);
    request.getSession().setAttribute("menu",menus);
  }

  /**
   * 初始化签到
   */
  private void initSign(String username) throws Exception {
    BbsUserSignSub userSignSub = bbsUserSignSubMapper.getUserSignSub(username);
    if (userSignSub == null) {
      userSignSub.setUpdateTime(new Date());
      userSignSub.setUsername(username);
      userSignSub.setCreateTime(new Date());
      userSignSub.setSuccessionDay(0);
      bbsUserSignSubMapper.insertSelective(userSignSub);
    } else {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      String now = format.format(new Date());
      if (userSignSub.getSuccessionDay().intValue() != 0) {//判断天数是否连续
        long wc = new Date().getTime() - userSignSub.getUpdateTime().getTime();
        int day = (int) (wc / (24 * 60 * 60 * 1000));
        if (day > 1) {
          bbsUserSignSubMapper.updateSuccessionDayToZero(username);//设为0
        }
      }
    }
  }
}
